/**
 * Copyright (c) 2015 www.smarthome.com All rights reserved. <br />
 * 本软件源代码版权归xxxx公司,未经许可不得任意复制与传播.<br />
 *
 */
package com.smarthome.core.user.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.smarthome.base.service.ShPropertyEmployeeService;
import com.smarthome.base.service.ShUserRoleService;
import com.smarthome.base.service.ShUserRoleSnapService;
import com.smarthome.base.service.ShUserService;
import com.smarthome.common.tools.SHACipher;
import com.smarthome.core.user.PropertyUserService;
import com.smarthome.domain.bean.ShPropertyEmployee;
import com.smarthome.domain.bean.ShUser;
import com.smarthome.domain.bean.ShUserRole;
import com.smarthome.domain.bean.ShUserRoleSnap;
import com.smarthome.domain.enums.ShUserSuperFlagEnum;
import com.smarthome.domain.vo.boss.DataGrid;
import com.smarthome.domain.vo.boss.PageHelper;

@Service("propertyUserService")
public class PropertyUserServiceImpl implements PropertyUserService {

    protected static Logger LOGGER;

    @Resource
    private ShUserService shUserService;
    
    @Resource(name="shUserRoleSnapService")
    private ShUserRoleSnapService userRoleSnapService;
    
    @Resource(name="shUserRoleService")
    private ShUserRoleService shUserRoleService;
    
    @Resource(name="shPropertyEmployeeService")
    private ShPropertyEmployeeService shPropertyEmployeeService;

    public PropertyUserServiceImpl() {
        LOGGER = LoggerFactory.getLogger(this.getClass());
    }

    @Override
    public ShUser queryPropertyUserByLoginName(String loginName) {
        ShUser shUser = new ShUser();
        shUser.setLoginName(loginName);
        List<ShUser> shPropertyUsers = shUserService.selectEntryList(shUser);
        if (null != shPropertyUsers && shPropertyUsers.size() == 1) {
            return shPropertyUsers.get(0);
        }
        return null;
    }

    @Override
    public ShUser queryPropertyUserById(Long userId) {
    	ShUser user =  shUserService.selectEntryById(userId);
    	List<ShUser> us = new ArrayList<ShUser>();
    	us.add(user);
    	us = addProperty(us);
    	try{
    		user = us.get(0);
    	} catch(Exception e){
    		e.printStackTrace();
    	}
    	return user;
    }

    @Override
    public DataGrid dataGrid(ShUser user, PageHelper page) {
    	DataGrid grid = shUserService.queryShUsers(user, page);
    	grid.setRows(addProperty(grid.getRows()));
        return grid;
    }
    
	@Override
	public List<ShUser> getUsers(ShUser user) {
		return shUserService.selectEntryList(user);
	}

	@Override
	public int add(ShUser user) {
		if(null == user) return 0;
		user.setStatus(1);
		user.setSuperFlag(ShUserSuperFlagEnum.NORMAL.getFlag());
		try {
			user.setLoginPwd(SHACipher.encrypt(user.getLoginPwd()));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		//插入用户
		int count = shUserService.insert(user);
		
		String roleIds = user.getRoleIds();
		Long userId = user.getId() ;
		
		if(null != userId&& !StringUtils.isBlank(roleIds)){
			String[] roles = roleIds.split(",");
			for(String r : roles){
				try{
					ShUserRoleSnap snap = new ShUserRoleSnap();
					snap.setRoleId( Long.parseLong(r));
					snap.setUserId(userId);
					userRoleSnapService.insert(snap);
				} catch(Exception e){
					e.printStackTrace();
				}
			}
			
		}
		
		return count;
	}

	@Override
	public int edit(ShUser user) {
		if(null == user || null == user.getId()) return 0;
		
		ShUser qu = shUserService.selectEntryById(user.getId());
		if(null == qu)	return 0;
		
		//防止页面更改用户名字
		user.setLoginName(qu.getLoginName());
		//防止页面更改员工
		user.setEmployeeId(qu.getEmployeeId());
		user.setLoginPwd(qu.getLoginPwd());
		//更新用户
		int count = shUserService.saveOrUpdate(user);
		
		String roleIds = user.getRoleIds();
		Long userId = user.getId() ;
		userRoleSnapService.deleteByUserId(userId);
		if( !StringUtils.isBlank(roleIds)){
			String[] roles = roleIds.split(",");
			for(String r : roles){
				try{
					ShUserRoleSnap snap = new ShUserRoleSnap();
					snap.setRoleId( Long.parseLong(r));
					snap.setUserId(userId);
					userRoleSnapService.insert(snap);
				} catch(Exception e){
					e.printStackTrace();
				}
			}
			
		}
		return count;
	}

	@Override
	public int delete(Long id) {
		if(null == id) return 0;
		int count = shUserService.deleteByIds(id);
		userRoleSnapService.deleteByUserId(id);
		
		return count;
	}
	@Override
	public int batchDelete(Long ... ids) {
		if(null == ids) return 0;
		int count = shUserService.deleteByIds(ids);
		userRoleSnapService.deleteByUserId(ids);
		return count;
	}

	@Override
	public void grant(ShUser user) {
		if(null == user ||null == user.getId()) return ;
		
		Long userId = user.getId();
		String roleIds = user.getRoleIds();
		userRoleSnapService.deleteByUserId(userId);
		if( !StringUtils.isBlank(roleIds)){
			String[] roles = roleIds.split(",");
			for(String r : roles){
				try{
					ShUserRoleSnap snap = new ShUserRoleSnap();
					snap.setRoleId( Long.parseLong(r));
					snap.setUserId(userId);
					userRoleSnapService.insert(snap);
				} catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}

	/* (non-Javadoc)
	 * @see com.smarthome.core.user.PropertyUserService#editPwd(com.smarthome.domain.bean.ShUser)
	 */
	@Override
	public void editPwd(ShUser user) {
		if(null == user || null == user.getId() || StringUtils.isBlank(user.getLoginPwd())) return;
		ShUser qu = shUserService.selectEntryById(user.getId());
		if(null == qu){
			return ;
		}
		
		try {
			qu.setLoginPwd(SHACipher.encrypt(user.getLoginPwd()));
			shUserService.saveOrUpdate(qu);
		} catch (Exception e) {
			LOGGER.info(e.getMessage());
		}
		
	}

	public boolean isRepeat(ShUser user) {
		boolean isRepeat = false;
		if(null == user || StringUtils.isBlank(user.getLoginName())){
			return isRepeat;
		}
		
		ShUser qu = new ShUser();
		qu.setLoginName(user.getLoginName());
		List<ShUser> list = shUserService.selectEntryList(qu);
		if(null == list || list.size() == 0){
			return isRepeat;
		}
		
		for(ShUser u : list){
			if((user.getLoginName() != null  && u.getLoginName() == null) ||  user.getLoginName().equals(u.getLoginName()) ){
				if(user.getId() != null && u.getId().equals(user.getId())){
					continue;
				}
				return true;
			}
		}
		
		
		return isRepeat;
	}

	@Override
	public boolean isRegest(ShUser user) {
		boolean isRepeat = false;
		if(null == user ||  null == user.getEmployeeId()){
			return isRepeat;
		}
		ShUser qu = new ShUser();
		qu.setEmployeeId(user.getEmployeeId());
		List<ShUser> list = shUserService.selectEntryList(qu);
		if(null == list || list.size() == 0){
			return isRepeat;
		}
		
		for(ShUser u : list){
			if((user.getEmployeeId() != null  && u.getEmployeeId() == null) ||  user.getEmployeeId().equals(u.getEmployeeId()) ){
				if(user.getId() != null && u.getId().equals(user.getId())){
					continue;
				}
				return true;
			}
		}
		
		return false;
	}

	@Override
	public List<ShUser> addProperty(List<ShUser> users) {
		if(null == users || users.size() == 0)  return users;
		
		Long[] ids = new Long[users.size()];
		Set<Long> employeeIds = new HashSet<Long>();
		for(int i=0;i<users.size();i++){
			ShUser u = users.get(i);
			ids[i] = u.getId();
			if(null != u.getEmployeeId()) employeeIds.add(u.getEmployeeId());
		}
		
		//查询角色
		List<ShUserRoleSnap> urs = userRoleSnapService.queryUserRoleByUserId(ids);
		Set<Long> roleIds = new HashSet<Long>();
		if(null == urs){
			urs = new ArrayList<ShUserRoleSnap>();
		}
		for(ShUserRoleSnap u : urs){
			roleIds.add(u.getRoleId());
		}
		List<ShUserRole>  userRoles = shUserRoleService.selectEntryListByIds(roleIds.toArray(new Long[]{}));
		
		Map<Long,ShUserRole> roleMap = new HashMap<Long,ShUserRole>();
		
		if(null != userRoles){
			for(ShUserRole r : userRoles){
				roleMap.put(r.getId(), r);
			}
		}
		
		//查询物业人员
		List<ShPropertyEmployee> employees = shPropertyEmployeeService.selectEntryListByIds(employeeIds.toArray(new Long[]{}));
		
		Map<Long,ShPropertyEmployee> employeeMap = new HashMap<Long,ShPropertyEmployee>();
		Map<Long,List<ShUserRole>> rolesMap = new HashMap<Long,List<ShUserRole>>();
		
		
		for(ShUserRoleSnap u : urs){
			List<ShUserRole> roles = rolesMap.get(u.getUserId());
			if(null == roles) {
				roles = new ArrayList<ShUserRole>();
				rolesMap.put(u.getUserId(), roles);
			}
			if(null != roleMap.get(u.getRoleId())){
				roles.add(roleMap.get(u.getRoleId()));
			}
		}
		
		if(null != employees){
			for(ShPropertyEmployee e : employees){
				employeeMap.put(e.getId(), e);
			}
		}
		
		
		for(ShUser user : users){
			ShPropertyEmployee e = employeeMap.get(user.getEmployeeId());
			if(null != e){
				user.setEmployeeName(e.getName());
				user.setEmployee(e);
			}
			
			List<ShUserRole> roles =rolesMap.get(user.getId());
			if(null != roles &&  roles.size() != 0){
				String roleids = "";
				String roleNames = "";
				
				for(ShUserRole r : roles){
					if(!"".equals(roleids))	roleids += ",";
					if(!"".equals(roleNames))		roleNames += ",";
					
					roleids += r.getId();
					roleNames += r.getName();
				}
				
				user.setRoleIds(roleids);
				user.setRoleNames(roleNames);	
				user.setRoles(userRoles);
			}
			
		}
		
		return users;
	}

	@Override
	public List<ShUser> queryPropertyUsersByIds(Long[] userIds) {
		
		return shUserService.selectEntryListByIds(userIds);
	}

}
